//
//  HELCompulsoryVC.m
//  sanda
//
//  Created by 陈武琦 on 16/7/12.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTDownloadVC.h"
#import "CWQ_courseIntroductionCell.h"
#import "BTCourseModel.h"
#import "BTCourseDetailVC.h"
#import "Masonry.h"

#import "BTCollectionBottomMenuView.h"
#import "ReaderFileViewController.h"
#import "RLMCourseManager.h"
#import "HELPDFfileCacheTool.h"
#import "RLMCourseManager.h"
#import "PDFReadFileJumper.h"
#import "HZPhotoBrowser.h"
#import "TYVideoPlayerController.h"
@interface BTDownloadVC ()<BTCollectionBottomMenuViewViewDelegate,HZPhotoBrowserDelegate>



@property(nonatomic, strong)BTCollectionBottomMenuView *bottomMenu;
@property (nonatomic, copy) NSMutableDictionary *deleteDic;
@property (nonatomic,  strong) UIButton *deleBtn;

@property (nonatomic,  strong) BTCourseModel *currentLongImageModel;


//加载的页面
@property (nonatomic, assign) NSInteger page;

@end


@implementation BTDownloadVC


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"下载";
    self.view.backgroundColor = [UIColor  whiteColor];
    [self setupSubviews];
    
}

- (void)setupSubviews {
  
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"CWQ_courseIntroductionCell" bundle:nil] forCellReuseIdentifier:@"CWQ_courseIntroductionCell"];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    UIButton *rightItemBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightItemBtn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
    self.deleBtn = rightItemBtn;
    [rightItemBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    rightItemBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    
    [rightItemBtn addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:rightItemBtn]];
    defineWeakSelf;
    [self.bottomMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(kScreenWidth+2, 44));
        make.left.equalTo(weakSelf.view).with.offset(0);
        make.top.equalTo(weakSelf.tableView.mas_bottom).with.offset(0);
        
    }];
    
    /*
     RLMRealm *realm = [RLMRealm defaultRealm]; // Create realm pointing to default file
     RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
     
     
     [realm beginWriteTransaction];
     NSString *icon = @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1473041357&di=124e43ce7e16f17cebc3a6143ff11dea&src=http://b.hiphotos.baidu.com/image/pic/item/d009b3de9c82d15825ffd75c840a19d8bd3e42da.jpg";
     for (int i = 0; i < 50; i++) {
     NSDictionary *dict = @{@"id":@(i), @"name":[NSString stringWithFormat:@"%d%d%d%d%d%d%d",i,i,i,i,i,i,i], @"attachUrlMap":@{@"mid":icon}, @"date":[NSString stringWithFormat:@"%d天后过期",i], @"persent":[NSString stringWithFormat:@"%d0%@",i, @"%"]};
     HELCompulsoryM *model = [HELCompulsoryM mj_objectWithKeyValues:dict];
     
     [realm addObject:model];
     
     }
     [realm commitWriteTransaction];
     // dispatch_async(dispatch_get_main_queue(), ^{
     
     
     [self.tableView cwq_requestDataWithDown:YES];
     //        });
     //    });
     
     */
 
    [self.tableView wsj_HeaderRefreshBlock:^{
        [weakSelf getCourseFormDB];
    }];
    [self getCourseFormDB];
    
}
- (void)dealloc{

}
- (void)getCourseFormDB{
   
    weakSelf_define;
    weakSelf.tableView.loading = YES;
    [[RLMCourseManager manager] getAllObjectsWithHandel:^(NSArray<BTCourseModel *> *array) {
         weakSelf.tableView.loading = NO;
        [weakSelf.dataArray removeAllObjects];
        [weakSelf.dataArray addObjectsFromArray:array];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.header endRefreshing];
    }];
}

- (void)deleteClick:(UIButton *)btn {
    
    self.tableView.editing = !self.tableView.editing;
    if (self.tableView.editing) {
        [btn setImage:nil forState:UIControlStateNormal];
        [btn setTitle:@"取消" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
      
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 44, 0));
        }];
    }else {
        
        [btn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
        [btn setTitle:@"" forState:UIControlStateNormal];
//        [self.deleteDic removeAllObjects];
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
}


- (BTCollectionBottomMenuView *)bottomMenu {
    if (!_bottomMenu) {
        _bottomMenu = [BTCollectionBottomMenuView menuView];
        _bottomMenu.delegate = self;
        [self.view addSubview:_bottomMenu];
    }
    
    return _bottomMenu;
    
}




- (NSMutableDictionary *)deleteDic {
    
    if (!_deleteDic) {
        _deleteDic = [@{} mutableCopy];
    }
    
    return _deleteDic;
}





#pragma mark - <UITableViewData and UITableDelegate>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CWQ_courseIntroductionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CWQ_courseIntroductionCell" forIndexPath:indexPath];
   
    BTCourseModel *model = self.dataArray[indexPath.row];
    cell.needShowGaizhang= YES;
    cell.courseModel = model;
    cell.tagKey = @"download";
  
  
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     BTCourseModel *model = [self.dataArray objectAtIndex:indexPath.row];
    if (tableView.editing) {
       
        [self.deleteDic setObject:model forKey:model.id];
        [self resetDeleteBtnTitle];
        return;
    }
    UITableViewCell *cell =[self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    NSInteger type =  [model.courseType integerValue];
    //pdf 课程  type 0
    switch (type) {
        case 0:
            
            [PDFReadFileJumper gotoPdfVCWith:cell withCourse:model fromVC:self toVC:[ReaderFileViewController new] withBackBlock:^{
                
            }];
            break;
        case 1:
           
            
            [self gotoVideoWithCourse:model];
            break;
        case 2:
          
            break;
        case 3:
            [self browserPicWithCourse:model];
            break;
        
            
        default:
            break;
    }
  
    
   
  
    
//    BTCourseModel *model = self.dataArray[indexPath.row];
   
   
}

- (void)gotoVideoWithCourse:(BTCourseModel *)course {
    // 测试用
    //    [BTNetworkManager sharedMg];
    TYVideoPlayerController *playerController = [[TYVideoPlayerController alloc]init];
    playerController.videoTitle = course.courseName;
    playerController.course = course;
    NSString *path = [HELPDFfileCacheTool isChchedWithPdfFilename:course.courseName isMP4:YES];
   
    if (path) {
        NSURL *url = [NSURL fileURLWithPath:path];
        playerController.streamURL =  url;
    }else{
        UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"文件已经删除!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [aler show];
        return;
    }
    
    
    [self presentViewController:playerController animated:YES completion:nil];
    //
    // VideoPlayerViewController *playvc = [VideoPlayerViewController new];
    //[self presentViewController:playvc animated:YES completion:nil];
    
}




- (void)resetDeleteBtnTitle {
    
    NSString *deleTitle;
    if ([self.deleteDic count] == 0) {
        deleTitle = @"删除";
    }else {
        
        deleTitle = [NSString stringWithFormat:@"删除(%lu)",(unsigned long)[self.deleteDic count]];
    }
    [self.bottomMenu.deleteBtn setTitle:deleTitle forState:UIControlStateNormal];
    
}


- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.editing) {
        BTCourseModel *model = [self.dataArray objectAtIndex:indexPath.row];
        [self.deleteDic removeObjectForKey:model.id];
        [self resetDeleteBtnTitle];
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

#pragma mark ----------------bottomMenu代理--------------------------
- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickSelectBtn:(UIButton *)button {
    if ([button.titleLabel.text isEqualToString:@"全选"]) {
        [button setTitle:@"全不选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataArray.count; i++) {
            BTCourseModel *model = [self.dataArray objectAtIndex:i];
            [self.deleteDic setObject:model forKey:model.id];
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES scrollPosition:NO];
            
        }
        
    }else {
        [button setTitle:@"全选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataArray.count; i++) {
            BTCourseModel *model = [self.dataArray objectAtIndex:i];
            [self.deleteDic removeObjectForKey:model.id];
            [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
            
        }
    }
    [self resetDeleteBtnTitle];
}

- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickDeleteBtn:(UIButton *)button {
    
    //删除数据库中对应的数据
    
    NSArray *models = [self.deleteDic allValues];
    if (models.count <= 0) {
        return;
    }
   
    
//    [[re sharedTool] deleCourseWithCourses:[self.deleteDic allValues]];
    weakSelf_define;
    [[RLMCourseManager manager] deleteCoursesWithCourseArr:[self.deleteDic allValues] doneBlock:^{
        [HELPDFfileCacheTool removePdfFileWithPdfNames:models];
        ;
        if ([weakSelf.deleteDic count] == weakSelf.dataArray.count) {
            
            [weakSelf.deleteDic removeAllObjects];
            [weakSelf.dataArray removeAllObjects];
            [button setTitle:@"删除" forState:UIControlStateNormal];
            [weakSelf.tableView reloadData];
            return;
        }
        
       
        [weakSelf.dataArray removeObjectsInArray:[weakSelf.deleteDic allValues]];
//        [weakSelf.dataArray enumerateObjectsUsingBlock:^(BTCourseModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [[weakSelf.deleteDic allValues] enumerateObjectsUsingBlock:^(BTCourseModel *  _Nonnull obj2, NSUInteger idx, BOOL * _Nonnull stop) {
//                if ( [obj2.id integerValue] == [obj.id integerValue]) {
//                    [weakSelf.dataArray removeObject:obj];
//                }
//            }];
//        }];
        [weakSelf.deleteDic removeAllObjects];
     
         [weakSelf.tableView reloadData];
        [button setTitle:@"删除" forState:UIControlStateNormal];
        
    }];
    [self deleteClick:self.deleBtn];
  
    
}

//浏览长图图片
- (void)browserPicWithCourse:(BTCourseModel *)course{
    weakSelf_define;
    //启动图片浏览器
    HZPhotoBrowser *browserVc = [[HZPhotoBrowser alloc] init];
     browserVc.course = course;
    browserVc.sourceImagesContainerView = weakSelf.view; // 原图的父控件
    browserVc.imageCount = 1; // 图片总数
    browserVc.currentImageIndex = 0;
    browserVc.courseName= course.courseName;
    browserVc.courseUrl = course.courseUrl;
    browserVc.delegate = self;
    self.currentLongImageModel = course;
    [browserVc showWithVC:weakSelf];
    
}

#pragma mark - photobrowser代理方法
- (UIImage *)photoBrowser:(HZPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    return [UIImage imageNamed:@"longimage.png"];
}
- (NSURL *)photoBrowser:(HZPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    if ([self.currentLongImageModel.courseType integerValue] == 3) {
        return [NSURL URLWithString:self.currentLongImageModel.courseUrl];
    }
    return nil;
}

@end
